#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
using namespace std;

class Solution {
public:
    int atoi(const char *str) {
        int sign = 1; 
        long long ans = 0;

        if (!str || *str == '\0') 
            return 0; 

        while (*str == ' ') {
            str++;
        }

        if (*str == '-') {
            sign = -1; 
            str++;
        } else if (*str == '+') {
            str++;
        }
        
        while (*str >= '0' && *str <= '9') {
            ans = 10*ans + (*str -'0');     
            if ((sign == 1 && ans >= INT_MAX) || (sign == -1 && -ans <= INT_MIN))
                return sign == -1? INT_MIN : INT_MAX;
            str++;
        }
        
        return sign * (int)ans;
    }
};

// test on online judge http://www.leetcode.com/onlinejudge and pass all test
int main(int argc, char **argv)
{
    Solution mySolution;
    int result;
    result = mySolution.atoi("123");
    cout << result << endl;

    result = mySolution.atoi("-237");
    cout << result << endl;
    result = mySolution.atoi("  237");
    cout << result << endl;
    result = mySolution.atoi("23877777777777");
    cout << result << endl;
    result = mySolution.atoi("-23877777777777");
    cout << result << endl;
}
